package com.linx.common.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linx.common.core.utils.HttpClientUtils;
import com.linx.common.core.utils.SpringUtils;
import com.linx.common.core.utils.StringUtils;
import com.linx.common.redis.utils.RedisUtils;
import com.linx.common.web.properties.JcptGisProperties;
import com.linx.common.web.properties.JcptHkProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/***
 * @ClassName GisTokenUtils
 * @Description Gistoken工具类
 * @Author gushaoliang
 * @Date 2024/12/19 上午11:02
 * @Version 1.0
 */
@Slf4j
@Component
public class GisTokenUtils {
    public static String url;
    public static String grantType;
    public static String clientId;
    public static String clientSecret;


    public GisTokenUtils() {
        JcptGisProperties jcptGisProperties = SpringUtils.getBean(JcptGisProperties.class);
        url = jcptGisProperties.getUrl();
        grantType = jcptGisProperties.getGrantType();
        clientId = jcptGisProperties.getClientId();
        clientSecret = jcptGisProperties.getClientSecret();
    }

    private static long tokenExpireTime = 0;
    private static String cachedAccessToken = null;

    /**
     * 获取token（缓存机制）
     *
     * @return token
     * @throws Exception 异常
     */
    public String getGisToken() {
        //url = "https://hzerodevgw.ysyec.com/oauth/oauth/token";
        //grantType = "client_credentials";
        //clientId = "hk-client";
        //clientSecret = "123qwe";
        // 解析返回结果
        String response = null;
        try {
            response = HttpClientUtils.sendPost(url + "?grant_type=" + grantType + "&client_id=" + clientId +
                    "&client_secret=" + clientSecret,
                null);
        } catch (IOException e) {
            throw new RuntimeException("获取Gistoken失败: " + e.getMessage());
        }

        log.info("统一平台GIS认证请求返回:" + response);
        // 解析返回结果
        JSONObject jsonResponse = JSON.parseObject(response);
        if (jsonResponse.containsKey("access_token")) {
            cachedAccessToken = jsonResponse.getString("access_token");

            return cachedAccessToken;
        } else {
            throw new RuntimeException("获取Gistoken失败: " + jsonResponse);
        }

    }


}
